//! 此测试脚本用于检测撮合引擎的基本功能
//!
//! 包括下单/撤单/成交匹配(交叉, 市价, 订单簿更新等)
#![allow(unused)]
use eztrade_core::{
    engine::MatchEngineTrait,
    exchange::{Exchange, ExchangeTrait},
};
use eztrade_dto::order::{Direction, Order, OrderStatus, PositionEffect};
use eztrade_dto::tick::{self, Orderstack, TickData};
use rstest::*;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::{sleep, timeout};
use tracing_appender;
use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};

/// 创建测试用的撮合引擎
fn create_match_exchange() -> Arc<Exchange> {
    Arc::new(Exchange::default())
}

/// 获取当前时间戳(微秒)
fn get_current_timestamp_us() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_micros() as u64
}

/// 创建测试订单的辅助函数
fn create_order(
    symbol: &str,
    direction: Direction,
    position_effect: PositionEffect,
    price: Option<f64>,
    quantity: u64,
) -> Order {
    Order {
        id: None, // 由引擎生成
        symbol: symbol.to_string(),
        direction,
        position_effect,
        price,
        quantity,
        status: OrderStatus::Unfilled,
        timestamp_us: None, // 由引擎生成
        inherited: false,
        next_id: 0,
        client_id: 0,
        is_limit: price.is_some(), // 如果有价格则为限价单
        frozen_price: None,
    }
}

/// 辅助函数：触发撮合引擎运行一次
async fn trigger_matching(engine: Arc<Exchange>) {
    // 启动撮合引擎并在短时间后停止
    let engine_task = tokio::spawn(engine.clone().run(10_000));

    // 等待一小段时间让撮合执行
    sleep(Duration::from_millis(100)).await;

    // 取消撮合引擎任务
    engine_task.abort();
}

/// 测试场景1: 基本限价单挂单成交
#[rstest]
#[tokio::test]
async fn test_limit_order_matching() {
    println!("=== 测试场景1: 基本限价单挂单成交 ===");

    let exchange = create_match_exchange();
    let symbol = "BTCUSDT";
    let timestamp = get_current_timestamp_us();

    // 1. 创建买单
    let buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        Some(50000.0), // 买入价格
        10,            // 数量
    );

    // 2. 创建卖单
    let sell_order = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        Some(49999.0), // 卖出价格 (低于买入价格，应该成交)
        8,             // 数量
    );

    // 执行测试流程
    println!("1. 挂买单...");
    let placed_buy = exchange.place_order(buy_order, 1001).unwrap();
    println!(
        "买单ID: {:?}, 价格: {:?}, 数量: {}",
        placed_buy.id, placed_buy.price, placed_buy.quantity
    );

    println!("2. 更新时间戳...");
    exchange.update_timestamp(timestamp);

    println!("3. 挂卖单...");
    let placed_sell = exchange.place_order(sell_order, 1002).unwrap();
    println!(
        "卖单ID: {:?}, 价格: {:?}, 数量: {}",
        placed_sell.id, placed_sell.price, placed_sell.quantity
    );

    println!("4. 执行撮合...");
    trigger_matching(exchange.clone()).await;

    // 验证结果
    let trades = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades {
        if !trades.is_empty() {
            let trade = trades.back().unwrap();
            println!("成交信息: {:?}", trade);
            println!(
                "成交数量: {}, 成交价格: {}",
                trade.quantity, trade.price_cent
            );
        }
    } else {
        assert!(false, "无成交记录");
    }

    // 检查活跃订单状态
    let active_orders_count = exchange.match_engine.active_orders.len();
    println!("当前活跃订单数: {}", active_orders_count);
    for entry in exchange.match_engine.active_orders.iter() {
        let order_id = entry.key();
        let order_ref = entry.value();
        let order = order_ref.read().unwrap();
        println!(
            "活跃订单ID: {}, 方向: {:?}, 价格: {:?}, 数量: {}, 状态: {:?}",
            order_id, order.direction, order.price, order.quantity, order.status
        );
    }

    println!("=== 测试场景1完成 ===\n");
}

/// 测试场景2: 闪电单(市价单)成交
#[rstest]
#[tokio::test]
async fn test_market_order_matching() {
    println!("=== 测试场景2: 闪电单(市价单)成交 ===");

    let exchange = create_match_exchange();
    let symbol = "ETHUSDT";
    let timestamp = get_current_timestamp_us();

    // 1. 先挂一个限价卖单作为对手盘
    let limit_sell_order = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        Some(3000.0), // 卖出价格
        5,            // 数量
    );

    // 2. 创建市价买单(闪电单)
    let market_buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        None, // 市价单，价格为None
        3,    // 数量
    );

    // 执行测试流程
    println!("1. 先挂限价卖单...");
    let placed_limit_sell = exchange.place_order(limit_sell_order, 2001).unwrap();
    println!("限价卖单: {:?}", placed_limit_sell);

    println!("2. 更新时间戳...");
    exchange.update_timestamp(timestamp);

    println!("3. 将订单队列放入订单簿...");
    // 刷新lastprice
    trigger_matching(exchange.clone()).await;

    println!("4. 挂市价买单(闪电单)...");
    let placed_market_buy = exchange.place_order(market_buy_order, 2002).unwrap();
    println!("市价买单: {:?}", placed_market_buy);

    println!("5. 再次将订单队列放入订单簿...");
    println!("6. 执行撮合...");
    trigger_matching(exchange.clone()).await;

    // 验证结果
    let trades = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades {
        if !trades.is_empty() {
            let trade = trades.back().unwrap();
            println!("成交信息: {:?}", trade);
        } else {
            assert!(false, "不应该无成交记录");
        }
    } else {
        assert!(false, "不应该无成交记录");
    }

    println!("=== 测试场景2完成 ===\n");
}

/// 测试场景3: 订单交叉成交(多个价位)
#[rstest]
#[tokio::test]
async fn test_cross_order_matching() {
    println!("=== 测试场景3: 订单交叉成交(多个价位) ===");

    let exchange = create_match_exchange();
    let symbol = "ADAUSDT";
    let timestamp = get_current_timestamp_us();

    // 创建多个不同价位的限价单
    let orders = vec![
        // 买单
        create_order(symbol, Direction::Long, PositionEffect::Open, Some(1.0), 1000),
        create_order(
            symbol,
            Direction::Long,
            PositionEffect::Open,
            Some(1.99),
            1500,
        ),
        create_order(
            symbol,
            Direction::Long,
            PositionEffect::Open,
            Some(1.98),
            2000,
        ),
        // 卖单
        create_order(
            symbol,
            Direction::Short,
            PositionEffect::Open,
            Some(1.97),
            1200,
        ),
        create_order(
            symbol,
            Direction::Short,
            PositionEffect::Open,
            Some(1.96),
            1800,
        ),
        create_order(
            symbol,
            Direction::Short,
            PositionEffect::Open,
            Some(1.95),
            2500,
        ),
    ];

    // 执行测试流程
    println!("1. 批量挂单...");
    let mut placed_orders = Vec::new();
    for (i, order) in orders.into_iter().enumerate() {
        let placed = exchange.place_order(order, 3000 + i as u64).unwrap();
        println!(
            "订单{}挂单成功, ID: {:?}, 方向: {:?}, 价格: {:?}, 数量: {}",
            i + 1,
            placed.id,
            placed.direction,
            placed.price,
            placed.quantity
        );
        placed_orders.push(placed);
    }

    println!("2. 更新时间戳...");
    exchange.update_timestamp(timestamp);

    println!("3. 执行撮合...");
    trigger_matching(exchange.clone()).await;

    // 验证结果
    let trades = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades {
        println!("成交记录数量: {}", trades.len());
        for (i, trade) in trades.iter().enumerate() {
            println!(
                "成交{}: 价格={}, 数量={}, 买单ID={}, 卖单ID={}",
                i + 1,
                trade.price_cent,
                trade.quantity,
                trade.id_long,
                trade.id_short
            );
        }
    } else {
        assert!(false, "预期有成交记录，但实际没有");
    }

    // 检查市场数据更新
    let tick_data = exchange.match_engine.tick_data.get(symbol);
    if let Some(tick_data) = tick_data {
        println!("最新tick数据: {:?}", tick_data.clone());
    } else {
        assert!(false, "预期有tick数据，但实际没有");
    }

    // Summary
    let summary = exchange.clearing_center.summary_all();
    println!("=== 交易统计 ===");
    println!("总交易数: {}", summary.total_trades);
    println!("总交易价值: {} 分", summary.total_trades_value_cents);
    println!("总手续费: {} 分", summary.total_fees_cents);
    println!("总账户余额: {} 分", summary.total_balance_cents);
    println!("总余额+手续费: {} 分", summary.balance_fees_cents);
    println!("===================");

    println!("=== 测试场景3完成 ===\n");
}

/// 测试场景4: 部分成交和订单拆分
#[rstest]
#[tokio::test]
async fn test_partial_fill_matching() {
    println!("=== 测试场景4: 部分成交和订单拆分 ===");

    let exchange = create_match_exchange();
    let symbol = "SOLUSDT";
    let timestamp = get_current_timestamp_us();

    // 1. 创建大额买单
    let large_buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        Some(100.0), // 买入价格
        50,          // 大数量
    );

    // 2. 创建小额卖单
    let small_sell_order1 = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        Some(99.0), // 卖出价格(低于买入价格)
        15,         // 小数量
    );

    let small_sell_order2 = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        Some(99.5), // 稍高的卖出价格
        20,         // 小数量
    );

    // 执行测试流程
    println!("1. 挂大额买单...");
    let placed_large_buy = exchange.place_order(large_buy_order, 4001).unwrap();
    println!(
        "大额买单ID: {:?}, 方向: {:?}, 价格: {:?}, 数量: {}",
        placed_large_buy.id,
        placed_large_buy.direction,
        placed_large_buy.price,
        placed_large_buy.quantity
    );

    println!("2. 更新时间戳...");
    exchange.update_timestamp(timestamp);

    println!("3. 将订单队列放入订单簿...");

    println!("4. 挂第一个小额卖单...");
    let placed_small_sell1 = exchange.place_order(small_sell_order1, 4002).unwrap();
    println!(
        "小额卖单1 ID: {:?}, 方向: {:?}, 价格: {:?}, 数量: {}",
        placed_small_sell1.id,
        placed_small_sell1.direction,
        placed_small_sell1.price,
        placed_small_sell1.quantity
    );

    println!("5. 将订单队列放入订单簿...");

    println!("6. 执行第一次撮合...");
    trigger_matching(exchange.clone()).await;

    println!("7. 挂第二个小额卖单...");
    let placed_small_sell2 = exchange.place_order(small_sell_order2, 4003).unwrap();
    println!(
        "小额卖单2 ID: {:?}, 方向: {:?}, 价格: {:?}, 数量: {}",
        placed_small_sell2.id,
        placed_small_sell2.direction,
        placed_small_sell2.price,
        placed_small_sell2.quantity
    );

    println!("8. 将订单队列放入订单簿...");

    println!("9. 执行第二次撮合...");
    trigger_matching(exchange.clone()).await;

    // 验证结果
    let trades = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades {
        println!("总成交记录数量: {}", trades.len());
        let total_traded_quantity: u64 = trades.iter().map(|t| t.quantity).sum();
        println!("总成交数量: {}", total_traded_quantity);

        for (i, trade) in trades.iter().enumerate() {
            println!(
                "成交{}: 价格={}, 数量={}, 多方={}, 空方={}",
                i + 1,
                trade.price_cent,
                trade.quantity,
                trade.id_long,
                trade.id_short
            );
        }
    } else {
        assert!(false, "预期有成交记录，但实际没有");
    }

    // 检查剩余活跃订单
    let active_orders_count = exchange.match_engine.active_orders.len();
    println!("剩余活跃订单数: {}", active_orders_count);
    for entry in exchange.match_engine.active_orders.iter() {
        let order_id = entry.key();
        let order_ref = entry.value();
        let order = order_ref.read().unwrap();
        println!(
            "活跃订单ID: {}, 方向: {:?}, 价格: {:?}, 数量: {}, 状态: {:?}",
            order_id, order.direction, order.price, order.quantity, order.status
        );
    }

    // Summary
    let summary = exchange.clearing_center.summary_all();
    println!("=== 交易统计 ===");
    println!("总交易数: {}", summary.total_trades);
    println!("总交易价值: {} 分", summary.total_trades_value_cents);
    println!("总手续费: {} 分", summary.total_fees_cents);
    println!("总账户余额: {} 分", summary.total_balance_cents);
    println!("总余额+手续费: {} 分", summary.balance_fees_cents);
    println!("===================");

    println!("=== 测试场景4完成 ===\n");
}

/// 测试场景5: 订单撤单
#[rstest]
#[tokio::test]
async fn test_order_cancellation() {
    println!("=== 测试场景5: 订单撤单 ===");

    let exchange = create_match_exchange();
    let symbol = "DOGEUSDT";
    let timestamp = get_current_timestamp_us();

    // 1. 创建订单
    let buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        Some(10.1), // 买入价格
        100,       // 数量
    );

    // 执行测试流程
    println!("1. 挂买单...");
    let placed_buy = exchange.place_order(buy_order, 5001).unwrap();
    let order_id = placed_buy.id.unwrap();
    println!(
        "买单ID: {}, 价格: {:?}, 数量: {}",
        order_id, placed_buy.price, placed_buy.quantity
    );

    // 激活交易所运行
    exchange.update_timestamp(timestamp);
    println!("2. 执行撮合...");
    trigger_matching(exchange.clone()).await;

    println!("3. 检查活跃订单...");
    if exchange.match_engine.active_orders.contains_key(&order_id) {
        println!("订单在活跃订单中");
    } else {
        assert!(false, "订单未在活跃订单中");
    }

    println!("4. 撤单...");
    let cancel_result = exchange.cancel_order(order_id, 5001);
    if cancel_result.is_ok() {
        println!("撤单成功");
    } else {
        println!("撤单失败: {:?}", cancel_result.err());
    }

    println!("5. 检查订单状态...");
    if exchange.match_engine.active_orders.contains_key(&order_id) {
        println!("仍在活跃订单中(未执行撮合)");
    } else {
        assert!(false, "买单不在活跃订单中，意外情况");
    }

    // 激活交易所运行
    trigger_matching(exchange.clone()).await;

    println!("6. 验证执行后已撤单...");
    if exchange.match_engine.active_orders.contains_key(&order_id) {
        println!("活跃订单中不存在(已执行撮合)");
    } else {
        assert!(false, "买单在活跃订单中，意外情况");
    }

    println!("完结订单数量: {}", exchange.match_engine.done_orders.len());

    println!("7. 验证撤单后无成交记录...");

    // 验证没有成交
    let trades = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades {
        if trades.is_empty() {
            println!("确认没有成交记录");
        } else {
            assert!(false, "意外的成交记录数量: {}", trades.len());
        }
    } else {
        println!("确认没有成交记录");
    }

    println!("=== 测试场景5完成 ===\n");
}

/// 测试场景6: 撤单后撮合验证
#[rstest]
#[tokio::test]
async fn test_cancel_then_match() {
    println!("=== 测试场景6: 撤单后撮合验证 ===");

    let exchange = create_match_exchange();
    let symbol = "LTCUSDT";
    let timestamp = get_current_timestamp_us();

    // 1. 创建买单和卖单
    let buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        Some(150.0), // 买入价格
        20,          // 数量
    );

    let sell_order = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        Some(149.0), // 卖出价格(低于买入价格，正常情况下会成交)
        15,          // 数量
    );

    // 执行测试流程
    println!("1. 挂买单...");
    let placed_buy = exchange.place_order(buy_order, 6001).unwrap();
    let buy_order_id = placed_buy.id.unwrap();
    println!(
        "买单ID: {}, 价格: {:?}, 数量: {}",
        buy_order_id, placed_buy.price, placed_buy.quantity
    );

    println!("2. 挂卖单...");
    let placed_sell = exchange.place_order(sell_order, 6002).unwrap();
    let sell_order_id = placed_sell.id.unwrap();
    println!(
        "卖单ID: {}, 价格: {:?}, 数量: {}",
        sell_order_id, placed_sell.price, placed_sell.quantity
    );

    println!("3. 更新时间戳...");
    exchange.update_timestamp(timestamp);

    println!("4. 撤销买单...");
    let cancel_result = exchange.cancel_order(buy_order_id, 6001);
    if cancel_result.is_ok() {
        println!("买单撤销指令已发送");
    } else {
        println!("买单撤销失败: {:?}", cancel_result.err());
    }

    println!("5. 执行撮合(需要撮合过程取消)...");
    trigger_matching(exchange.clone()).await;

    // 验证结果
    let trades = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades {
        if trades.is_empty() {
            println!("确认没有成交记录(符合预期)");
        } else {
            assert!(false, "意外的成交记录数量: {}", trades.len());
        }
    } else {
        println!("确认没有成交记录(符合预期)");
        let tick_data = exchange.match_engine.get_last_order_book(symbol);
        if let Some(tick_data) = tick_data {
            println!("最新行情数据: {:?}", tick_data);
        }
    }

    // 检查订单状态
    match exchange.query_order(buy_order_id, 6001) {
        Some(
            order @ Order {
                status: OrderStatus::Canceled,
                ..
            },
        ) => {
            println!("买单已取消");
        }
        _ => {
            assert!(false, "意外情况");
        }
    }

    match exchange.query_order(sell_order_id, 6002) {
        Some(
            order @ Order {
                status: OrderStatus::Unfilled,
                ..
            },
        ) => {
            println!("卖单仍未成交");
        }
        _ => {
            assert!(false, "意外情况");
        }
    }

    println!("=== 测试场景6完成 ===\n");
}

/// 测试场景7: 正常买卖价差下的市价单撮合
#[rstest]
#[tokio::test]
async fn test_market_order_with_spread() {
    println!("=== 测试场景7: 正常买卖价差下的市价单撮合 ===");

    let exchange = create_match_exchange();
    let symbol = "BNBUSDT";
    let timestamp = get_current_timestamp_us();

    // 1. 先建立正常的买卖价差：买1价格10，卖1价格11
    let limit_buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        Some(100.0), // 买1价格
        20,         // 数量
    );

    let limit_sell_order = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        Some(110.0), // 卖1价格
        25,         // 数量
    );

    // 2. 创建市价买单（应该以卖1价格11成交）
    let market_buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        None, // 市价单
        5,    // 数量
    );

    // 3. 创建市价卖单（应该以买1价格10成交）
    let market_sell_order = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        None, // 市价单
        8,    // 数量
    );

    // 执行测试流程
    println!("1. 建立价差：挂买1限价单(价格10)...");
    let placed_limit_buy = exchange.place_order(limit_buy_order, 7001).unwrap();
    println!(
        "买1限价单ID: {:?}, 价格: {:?}, 数量: {}",
        placed_limit_buy.id, placed_limit_buy.price, placed_limit_buy.quantity
    );

    println!("2. 建立价差：挂卖1限价单(价格11)...");
    let placed_limit_sell = exchange.place_order(limit_sell_order, 7002).unwrap();
    println!(
        "卖1限价单ID: {:?}, 价格: {:?}, 数量: {}",
        placed_limit_sell.id, placed_limit_sell.price, placed_limit_sell.quantity
    );

    println!("3. 更新时间戳...");
    exchange.update_timestamp(timestamp);

    println!("4. 将限价单放入订单簿...");
    trigger_matching(exchange.clone()).await;

    // 验证订单簿状态：应该有买卖价差，无成交
    let trades_before = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades_before {
        if trades.is_empty() {
            println!("确认限价单建立价差，无成交(符合预期)");
        } else {
            assert!(false, "限价单不应该成交，存在意外成交: {}", trades.len());
        }
    } else {
        println!("确认限价单建立价差，无成交(符合预期)");
    }

    println!("5. 挂市价买单(应以卖1价格11成交)...");
    let placed_market_buy = exchange.place_order(market_buy_order, 7003).unwrap();
    println!(
        "市价买单ID: {:?}, 转换后价格: {:?}, 数量: {}",
        placed_market_buy.id, placed_market_buy.price, placed_market_buy.quantity
    );

    println!("6. 执行撮合(市价买单)...");
    trigger_matching(exchange.clone()).await;

    // 验证市价买单成交
    let trades_after_buy = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades_after_buy {
        if !trades.is_empty() {
            let trade = trades.back().unwrap();
            println!(
                "市价买单成交: 价格={}, 数量={}, 买单ID={}, 卖单ID={}",
                trade.price_cent, trade.quantity, trade.id_long, trade.id_short
            );
            assert_eq!(trade.price_cent, 11000, "市价买单应该以卖1价格11成交");
            assert_eq!(trade.quantity, 5, "成交数量应该为5");
        } else {
            assert!(false, "市价买单应该成交");
        }
    } else {
        assert!(false, "市价买单应该成交");
    }

    println!("7. 挂市价卖单(应以买1价格10成交)...");
    let placed_market_sell = exchange.place_order(market_sell_order, 7004).unwrap();
    println!(
        "市价卖单ID: {:?}, 转换后价格: {:?}, 数量: {}",
        placed_market_sell.id, placed_market_sell.price, placed_market_sell.quantity
    );

    println!("8. 执行撮合(市价卖单)...");
    trigger_matching(exchange.clone()).await;

    // 验证市价卖单成交
    let trades_final = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades_final {
        if !trades.is_empty() {
            let trade = trades.back().unwrap();
            println!(
                "市价卖单成交: 价格={}, 数量={}, 买单ID={}, 卖单ID={}",
                trade.price_cent, trade.quantity, trade.id_long, trade.id_short
            );
        } else {
            assert!(false, "市价卖单应该成交");
        }
    } else {
        assert!(false, "市价卖单应该成交");
    }

    // 验证最终状态
    println!("9. 验证最终订单簿状态...");
    let final_trades = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = final_trades {
        println!("总成交记录数: {}", trades.len());
        for (i, trade) in trades.iter().enumerate() {
            println!(
                "成交{}: 价格={}, 数量={}, 买方={}, 卖方={}",
                i + 1,
                trade.price_cent,
                trade.quantity,
                trade.id_long,
                trade.id_short
            );
        }
    }

    // 检查剩余活跃订单
    let active_orders_count = exchange.match_engine.active_orders.len();
    println!("剩余活跃订单数: {}", active_orders_count);
    for entry in exchange.match_engine.active_orders.iter() {
        let order_id = entry.key();
        let order_ref = entry.value();
        let order = order_ref.read().unwrap();
        println!(
            "活跃订单ID: {}, 方向: {:?}, 价格: {:?}, 剩余数量: {}, 状态: {:?}",
            order_id, order.direction, order.price, order.quantity, order.status
        );
    }

    // Summary
    let summary = exchange.clearing_center.summary_all();
    println!("=== 交易统计 ===");
    println!("总交易数: {}", summary.total_trades);
    println!("总交易价值: {} 分", summary.total_trades_value_cents);
    println!("总手续费: {} 分", summary.total_fees_cents);
    println!("总账户余额: {} 分", summary.total_balance_cents);
    println!("总余额+手续费: {} 分", summary.balance_fees_cents);
    println!("===================");

    println!("=== 测试场景7完成 ===\n");
}

/// 测试场景8: 同时挂市价买卖单执行撮合
#[rstest]
#[tokio::test]
async fn test_simultaneous_market_orders() {
    println!("=== 测试场景8: 同时挂市价买卖单执行撮合 ===");

    let exchange = create_match_exchange();
    let symbol = "AVAXUSDT";
    let timestamp = get_current_timestamp_us();

    // 1. 先建立基础订单簿（为市价单提供参考价格）
    let base_buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        Some(20.0), // 基础买价
        100,        // 数量
    );

    let base_sell_order = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        Some(21.0), // 基础卖价
        100,        // 数量
    );

    // 2. 创建同时提交的市价单
    let market_buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        None, // 市价买单
        15,   // 数量
    );

    let market_sell_order = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        None, // 市价卖单
        12,   // 数量
    );

    // 执行测试流程
    println!("1. 建立基础订单簿...");
    let placed_base_buy = exchange.place_order(base_buy_order, 8001).unwrap();
    println!(
        "基础买单ID: {:?}, 价格: {:?}, 数量: {}",
        placed_base_buy.id, placed_base_buy.price, placed_base_buy.quantity
    );

    let placed_base_sell = exchange.place_order(base_sell_order, 8002).unwrap();
    println!(
        "基础卖单ID: {:?}, 价格: {:?}, 数量: {}",
        placed_base_sell.id, placed_base_sell.price, placed_base_sell.quantity
    );

    println!("2. 更新时间戳...");
    exchange.update_timestamp(timestamp);

    println!("3. 将基础订单放入订单簿...");
    trigger_matching(exchange.clone()).await;

    // 验证基础订单簿建立
    let trades_before = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades_before {
        if trades.is_empty() {
            println!("确认基础订单簿建立，无成交(符合预期)");
        } else {
            assert!(false, "基础订单不应该成交，存在意外成交: {}", trades.len());
        }
    } else {
        println!("确认基础订单簿建立，无成交(符合预期)");
    }

    println!("4. 同时挂入市价买单和市价卖单...");
    let placed_market_buy = exchange.place_order(market_buy_order, 8003).unwrap();
    println!(
        "市价买单ID: {:?}, 转换后价格: {:?}, 数量: {}",
        placed_market_buy.id, placed_market_buy.price, placed_market_buy.quantity
    );

    let placed_market_sell = exchange.place_order(market_sell_order, 8004).unwrap();
    println!(
        "市价卖单ID: {:?}, 转换后价格: {:?}, 数量: {}",
        placed_market_sell.id, placed_market_sell.price, placed_market_sell.quantity
    );

    println!("5. 执行撮合(处理同时提交的市价单)...");
    trigger_matching(exchange.clone()).await;

    // 验证市价单成交结果
    let trades_after = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades_after {
        if !trades.is_empty() {
            println!("市价单成交记录数: {}", trades.len());
            for (i, trade) in trades.iter().enumerate() {
                println!(
                    "成交{}: 价格={}, 数量={}, 买单ID={}, 卖单ID={}",
                    i + 1,
                    trade.price_cent,
                    trade.quantity,
                    trade.id_long,
                    trade.id_short
                );
            }

            // 验证成交逻辑
            let last_trade = trades.back().unwrap();
            if trades.len() == 1 {
                // 如果只有一笔成交，说明市价单之间直接撮合
                println!("市价单直接撮合成交");
                assert_eq!(last_trade.quantity, 12, "成交数量应该是较小的市价卖单数量");
            } else {
                // 如果有多笔成交，说明市价单与基础订单簿撮合
                println!("市价单与基础订单簿撮合");
            }
        } else {
            assert!(false, "应该有成交记录");
        }
    } else {
        assert!(false, "应该有成交记录");
    }

    println!("6. 验证剩余订单状态...");
    let active_orders_count = exchange.match_engine.active_orders.len();
    println!("剩余活跃订单数: {}", active_orders_count);

    for entry in exchange.match_engine.active_orders.iter() {
        let order_id = entry.key();
        let order_ref = entry.value();
        let order = order_ref.read().unwrap();
        println!(
            "活跃订单ID: {}, 方向: {:?}, 价格: {:?}, 剩余数量: {}, 状态: {:?}",
            order_id, order.direction, order.price, order.quantity, order.status
        );
    }

    // 检查订单状态变化
    let done_orders_count = exchange.match_engine.done_orders.len();
    println!("完结订单数: {}", done_orders_count);

    // 验证市价单的处理结果
    if let Some(market_buy_id) = placed_market_buy.id {
        if exchange
            .match_engine
            .done_orders
            .contains_key(&market_buy_id)
        {
            println!("市价买单已完成");
        } else if exchange
            .match_engine
            .active_orders
            .contains_key(&market_buy_id)
        {
            let order_ref = exchange
                .match_engine
                .active_orders
                .get(&market_buy_id)
                .unwrap();
            let order = order_ref.read().unwrap();
            println!("市价买单部分成交，剩余数量: {}", order.quantity);
        }
    }

    if let Some(market_sell_id) = placed_market_sell.id {
        if exchange
            .match_engine
            .done_orders
            .contains_key(&market_sell_id)
        {
            println!("市价卖单已完成");
        } else if exchange
            .match_engine
            .active_orders
            .contains_key(&market_sell_id)
        {
            let order_ref = exchange
                .match_engine
                .active_orders
                .get(&market_sell_id)
                .unwrap();
            let order = order_ref.read().unwrap();
            println!("市价卖单部分成交，剩余数量: {}", order.quantity);
        }
    }

    println!("=== 测试场景8完成 ===\n");
}

/// 测试场景9: 空订单簿下的市价单对撞
#[rstest]
#[tokio::test]
async fn test_market_orders_collision_empty_book() {
    println!("=== 测试场景9: 空订单簿下的市价单对撞 ===");

    let exchange = create_match_exchange();
    let symbol = "MATICUSDT";
    let timestamp = get_current_timestamp_us();

    // 创建同时提交的市价单（无基础订单簿）
    let market_buy_order = create_order(
        symbol,
        Direction::Long,
        PositionEffect::Open,
        None, // 市价买单
        30,   // 数量
    );

    let market_sell_order = create_order(
        symbol,
        Direction::Short,
        PositionEffect::Open,
        None, // 市价卖单
        25,   // 数量
    );

    // 执行测试流程
    println!("1. 确认订单簿为空...");
    let trades_initial = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades_initial {
        assert!(trades.is_empty(), "初始订单簿应该为空");
    }
    println!("订单簿确认为空");

    println!("2. 更新时间戳...");
    exchange.update_timestamp(timestamp);

    println!("3. 同时挂入市价买单和市价卖单(空订单簿)...");
    let placed_market_buy = exchange.place_order(market_buy_order, 9001).unwrap();
    println!(
        "市价买单ID: {:?}, 转换后价格: {:?}, 数量: {}",
        placed_market_buy.id, placed_market_buy.price, placed_market_buy.quantity
    );

    let placed_market_sell = exchange.place_order(market_sell_order, 9002).unwrap();
    println!(
        "市价卖单ID: {:?}, 转换后价格: {:?}, 数量: {}",
        placed_market_sell.id, placed_market_sell.price, placed_market_sell.quantity
    );

    println!("4. 执行撮合(空订单簿市价单对撞)...");
    trigger_matching(exchange.clone()).await;

    // 验证空订单簿下的市价单处理
    let trades_after = exchange.clearing_center.trades.get(symbol);
    if let Some(trades) = trades_after {
        if !trades.is_empty() {
            println!("空订单簿市价单成交记录数: {}", trades.len());
            for (i, trade) in trades.iter().enumerate() {
                println!(
                    "成交{}: 价格={}, 数量={}, 买单ID={}, 卖单ID={}",
                    i + 1,
                    trade.price_cent,
                    trade.quantity,
                    trade.id_long,
                    trade.id_short
                );
            }

            let trade = trades.back().unwrap();
            assert_eq!(trade.quantity, 25, "成交数量应该是较小的市价卖单数量");
            println!("空订单簿下市价单直接对撞成交");
        } else {
            println!("空订单簿下市价单未成交1");
        }
    } else {
        println!("空订单簿下市价单未成交2");
    }

    println!("5. 验证最终订单状态...");
    let active_orders_count = exchange.match_engine.active_orders.len();
    let done_orders_count = exchange.match_engine.done_orders.len();
    println!(
        "剩余活跃订单数: {}, 完结订单数: {}",
        active_orders_count, done_orders_count
    );

    for entry in exchange.match_engine.active_orders.iter() {
        let order_id = entry.key();
        let order_ref = entry.value();
        let order = order_ref.read().unwrap();
        println!(
            "活跃订单ID: {}, 方向: {:?}, 价格: {:?}, 剩余数量: {}, 状态: {:?}",
            order_id, order.direction, order.price, order.quantity, order.status
        );
    }

    println!("=== 测试场景9完成 ===\n");
}

#[tokio::main]
async fn main() {
    let file_appender = tracing_appender::rolling::daily("logs", "app.log");
    let (non_blocking_file, _guard) = tracing_appender::non_blocking(file_appender);
    use std::io;
    tracing_subscriber::registry()
        .with(
            // 控制台输出层
            fmt::layer().with_writer(io::stdout).with_ansi(true),
        )
        .with(
            // 文件输出层
            fmt::layer().with_writer(non_blocking_file).with_ansi(false),
        )
        .with(EnvFilter::from_default_env().add_directive("trace".parse().unwrap()))
        .init();

    // tracing_subscriber::fmt().with_max_level(tracing::Level::TRACE).init();
    // test_market_order_with_spread().await;
}
